package com.pinhuba.bams.framework.controller;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.widget.ImageView;
import android.widget.TextView;
import com.pinhuba.bams.framework.util.Loger;

public class DocDownloadLoadManager {
	private static List<AsynDocDownLoadLoader> taskList;
	static {
		taskList = new ArrayList<AsynDocDownLoadLoader>();
	}

	/**
	 * 添加一个下载任务到任务队列
	 * 
	 * @param loader
	 */
	public static synchronized void addTask(AsynDocDownLoadLoader loader) {
		if (taskList != null) {
			taskList.add(loader);
		}
	}

	/**
	 * 终止并删除所有任务
	 */
	public static synchronized void clearAll() {
		if (taskList != null) {
			for (AsynDocDownLoadLoader loader : taskList) {
				loader.cancel(true);
			}
			taskList.clear();
		}
	}

	/**
	 * 删除一个任务
	 * 
	 * @param loader
	 */
	public static synchronized void removeTask(AsynDocDownLoadLoader loader) {
		if (taskList != null) {
			if (loader != null) {
				loader.cancel(true);
			}
			taskList.remove(loader);
		}
	}

	public static synchronized boolean exists(String url) {
		Loger.d("The masklist size is:" + taskList.size());
		for (int i = 0; i < taskList.size(); i++) {
			if (url != null && url.equals(taskList.get(i).getDownloadURL())) {
				return true;
			}
		}
		return false;
	}

	public static int load(Activity context, String filePath, String docURL, ImageView iv, TextView tv, int position, DocDownloadCallBackListener callbck) {
		if (exists(docURL)) {
			return -1;
		}
		AsynDocDownLoadLoader Loader = new AsynDocDownLoadLoader(context, filePath, position, iv, tv, callbck);
		addTask(Loader);
		Loader.execute(docURL);
		return 0;
	}

}
